<script lang="ts" setup>
import { getPatientOrderLogisticsByIdAPI } from '@/apis/order'
import type { GetPatientOrderLogisticsData } from '@/types/order'
import type { DrivingData } from '@/types/qqmap'
import { ref } from 'vue'

// 1. 获取页面参数
const props = defineProps<{
  orderId: string // 药品订单ID
}>()

// 2. 获取物流信息
const orderLogistics = ref<GetPatientOrderLogisticsData>()
const getPatientOrderLogistics = async () => {
  // 发送请求并保存数据
  const res = await getPatientOrderLogisticsByIdAPI(props.orderId)
  orderLogistics.value = res.data
  // 物流信息获取成功后，获取行车路径
  getDrivingRoute()
}
getPatientOrderLogistics()

// 3. 获取地图坐标
//中心经纬度
const latitude = ref(39.90872)
const longitude = ref(116.39748)
//缩放比例
const scale = ref(11)
// 地图标记点
const markers = ref<UniHelper.MapMarker[]>([])
// 地图路线
const polyline = ref<UniHelper.MapPolyline[]>([])

// 4.获取行车路线
const getDrivingRoute = async () => {
  //起点
  const start = orderLogistics.value?.logisticsInfo.shift()
  //终点
  const end = orderLogistics.value?.logisticsInfo.pop()
  //途径点
  const waypoints = orderLogistics.value?.logisticsInfo
  // 当前位置
  const currentLocationInfo = orderLogistics.value?.currentLocationInfo

  uni.request({
    method: 'GET',
    url: 'https://apis.map.qq.com/ws/direction/v1/driving/',
    // #ifdef H5
    // @ts-ignore
    url: '/ws/direction/v1/driving/',
    // #endif
    data: {
      key: '2PPBZ-XWEKZ-HQHXW-ZB2JK-I2V6Q-H6BQS', // 腾讯地图key
      from: `${start?.latitude},${start?.longitude}`, // 起点坐标
      to: `${end?.latitude},${end?.longitude}`, // 终点坐标
      waypoints: waypoints?.map((v) => `${v.latitude},${v.longitude}`).join(';'), // 途径点
    },
    success: (res) => {
      // 获取驾车路线规划数据
      var result = (res.data as DrivingData).result
      var route = result.routes[0]

      var coors = route.polyline,
        pl = []
      //坐标解压（返回的点串坐标，通过前向差分进行压缩）
      var kr = 1000000
      for (var i = 2; i < coors.length; i++) {
        coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
      }
      //将解压后的坐标放入点串数组pl中
      for (var i = 0; i < coors.length; i += 2) {
        pl.push({ latitude: coors[i], longitude: coors[i + 1] })
      }
      polyline.value.push({
        points: pl, // 路线点解压后的坐标数组
        color: '#58c16c', // 路线颜色
        width: 6, // 路线宽度
        borderColor: '#2f693c', // 路线边框颜色
        borderWidth: 1, // 路线边框宽度
        arrowLine: true, // 路线箭头
      })

      //添加标记
      markers.value.push(
        {
          id: Date.now(),
          longitude: Number(start?.longitude),
          latitude: Number(start?.latitude),
          iconPath: '/static/images/start.png',
          width: 50,
          height: 60,
        },
        {
          id: Date.now() + 1,
          longitude: Number(end?.longitude),
          latitude: Number(end?.latitude),
          iconPath: '/static/images/end.png',
          width: 50,
          height: 60,
        },
        {
          id: Date.now() + 2,
          longitude: Number(currentLocationInfo?.longitude),
          latitude: Number(currentLocationInfo?.latitude),
          iconPath: '/static/images/car.png',
          width: 50,
          height: 30,
        }
      )

      // 先设置地图中心点为起始点
      latitude.value = Number(start?.latitude)
      longitude.value = Number(start?.longitude)
      // 设置地图缩放比例
      scale.value = 10

      //2秒后，设置地图中心点为当前位置
      setTimeout(() => {
        latitude.value = Number(currentLocationInfo?.latitude)
        longitude.value = Number(currentLocationInfo?.longitude)
        scale.value = 16
      }, 2000)
    },
  })
}
</script>

<template>
  <view class="timeline-page">
    <!-- 地图组件 -->
    <map
      id="map"
      class="uni-map"
      :latitude="latitude"
      :longitude="longitude"
      :scale="scale"
      :markers="markers"
      :polyline="polyline"
    ></map>
    <!--  物流信息 -->
    <cover-view class="timeline-meta">
      <cover-view class="status">{{ orderLogistics?.statusValue }}</cover-view>
      <cover-view class="extra">
        预计 {{ orderLogistics?.estimatedTime }} 送达
        {{ orderLogistics?.name }}
        {{ orderLogistics?.awbNo }}
      </cover-view>
    </cover-view>
    <view class="timeline-detail">
      <view class="title">物流详情</view>
      <view class="timeline">
        <view class="line">
          <view class="badge text">收</view>
          <view class="content"> 收货地址：广东省广州市大华区明离路科技园880号 </view>
        </view>

        <view v-for="item in orderLogistics?.list" :key="item.id" class="line">
          <!-- 1已发货 2已揽件 3 运输中 4 派送中 5已签收 -->
          <view class="badge dot" v-if="item.status <= 3"></view>

          <view class="badge icon" v-else-if="item.status === 4">
            <uni-icons color="#2cb5a5" custom-prefix="iconfont" type="icon-truck" />
          </view>

          <view class="badge icon" v-else-if="item.status === 5">
            <uni-icons color="#2cb5a5" custom-prefix="iconfont" type="icon-checked" />
          </view>

          <view class="label">{{ item.statusValue }}</view>
          <view class="content">{{ item.content }}</view>
          <view class="time">{{ item.createTime }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
